package com.hsc.account;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import com.hsc.db.tools.AccountList;
import com.hsc.db.tools.AccountService;
import com.hsc.db.tools.EmailService;
import com.hsc.db.tools.ItemService;
import com.hsc.db.tools.UseItemService;
import com.hsc.db.tools.useitem;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.ColorStateList;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.text.format.Time;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class twoActivity extends Activity {
	private GridView typeview;
	private TextView datetime;
	private  UseItemService typeService;
	private  AccountService accs;
	public  int iyear;
	public  int imonth;
	public  int iday;
	public TextView newtype;
	public TextView pmonth;
	public TextView nmonth;
	public TextView addone;
	public static int gv=-1;
	private ListView listView;
	private  List<AccountList> cur;
	private static ItemService items;
	public static  String curtype="-1";
	private AccountList lacc;
	private int aid;
	public static int pagenum=10;
	private int totalItem=0;

	private int cmonth;
	private int cyear;
	private LinearLayout llayout;
	private  ColorStateList bcolor;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.two);

		typeService = new UseItemService(this);
		accs = new AccountService(this);
		items = new ItemService(this);


		Time time = new Time();
		time.setToNow();

		Intent intent = getIntent();
		if(intent !=null)
		{
			iyear  = intent.getIntExtra("year", time.year);
			cyear=iyear;
			imonth  = intent.getIntExtra("month", time.month+1);
			cmonth=imonth;
			iday  = intent.getIntExtra("day",time.monthDay);
		}

		llayout = (LinearLayout)this.findViewById(R.id.layout_bottom);
		pmonth = (TextView)this.findViewById(R.id.pmonth);
		nmonth = (TextView)this.findViewById(R.id.nmonth);
		newtype = (TextView)this.findViewById(R.id.newtype);
		datetime = (TextView)this.findViewById(R.id.datetime);
		addone = (TextView)this.findViewById(R.id.btn_frame);

		bcolor = addone.getTextColors();


		datetime.setOnLongClickListener(new OnLongClickListener() {

			@Override
			public boolean onLongClick(View v) {


				AlertDialog.Builder builder = new AlertDialog.Builder(twoActivity.this);
				builder.setMessage("确定要上传吗？");

				builder.setPositiveButton("上传", new DialogInterface.OnClickListener(){

					@Override
					public void onClick(DialogInterface dialog,
										int which) {
						ArrayList<useitem> arr = typeService.getDataSuc();

						sendTypeThread sd = new sendTypeThread(arr, items);
						sd.start();

						Toast.makeText(twoActivity.this, "上传成功",
								Toast.LENGTH_SHORT).show();

					}});

				builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						dialog.dismiss();
					}
				}) ;
				builder.create().show();


				return false;
			}
		});


		pmonth.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				imonth--;
				if(imonth==0)
				{
					iyear--;
					imonth=12;
				}

				curtype="-1";
				gv=-1;

				newtype.setText(String.format("%.1f",accs.getZSum("1",iyear,imonth)));
				datetime.setText(String.valueOf(iyear)+"年"+String.format("%02d", imonth)+"月");

				cur = accs.getListDataByType(iyear,imonth,"XX",pagenum,0);
				//显示查询数据
				ListViewAdapter adapter = new ListViewAdapter(twoActivity.this,cur,items);
				listView.setAdapter(adapter);
				listView.setDivider(new ColorDrawable(Color.GRAY));
				listView.setDividerHeight(1);

				if(cmonth==imonth && cyear==iyear)
				{
					loadGridData();
					llayout.setVisibility(View.VISIBLE);
					newtype.setClickable(true);
				}else
				{
					loadGroupData();
					llayout.setVisibility(View.GONE);
					newtype.setClickable(false);
				}


			}
		});

		nmonth.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				imonth++;
				if(imonth==13)
				{
					iyear++;
					imonth=1;
				}

				curtype="-1";
				gv=-1;

				newtype.setText(String.format("%.1f",accs.getZSum("1",iyear,imonth)));
				datetime.setText(String.valueOf(iyear)+"年"+String.format("%02d", imonth)+"月");

				cur = accs.getListDataByType(iyear,imonth,"XX",pagenum,0);
				//显示查询数据
				ListViewAdapter adapter = new ListViewAdapter(twoActivity.this,cur,items);
				listView.setAdapter(adapter);
				listView.setDivider(new ColorDrawable(Color.GRAY));
				listView.setDividerHeight(1);

				if(cmonth==imonth && cyear==iyear)
				{
					loadGridData();
					llayout.setVisibility(View.VISIBLE);
					newtype.setClickable(true);

				}else
				{
					loadGroupData();
					llayout.setVisibility(View.GONE);
					newtype.setClickable(false);
				}
			}
		});



		newtype.setText(String.format("%.1f",accs.getZSum("1",iyear,imonth)));


		datetime.setText(String.valueOf(iyear)+"年"+String.format("%02d", imonth)+"月");

		listView = (ListView) this.findViewById(R.id.listView);
		typeview = (GridView) findViewById(R.id.typeview);

		//加载数据
		loadGridData();

		typeview.setOnItemLongClickListener(new OnItemLongClickListener() {

			@Override
			public boolean onItemLongClick(AdapterView<?> parent, View view,
										   int position, long id) {

				final HashMap<String, Object> map = (HashMap<String, Object>)parent.getItemAtPosition(position);

				AlertDialog.Builder builder = new AlertDialog.Builder(twoActivity.this);
				builder.setMessage("确定要删除吗？");

				builder.setPositiveButton("删除", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						String type = map.get("type").toString();
						//typeService.deleteByType(type);
						typeService.updateFlag(type,"0");

						useitem item = new useitem();
						item.setFlag("0");
						item.setUsetype(type);

						ArrayList<useitem> arr = new ArrayList<useitem>();
						arr.add(item);

						ItemService items = new ItemService(twoActivity.this);
						sendTypeThread sd = new sendTypeThread(arr, items);
						sd.start();

						if(cmonth==imonth && cyear==iyear)
						{
							loadGridData();
							addone.setEnabled(true);
							addone.setTextColor(bcolor);

						}else
						{
							loadGroupData();
							addone.setEnabled(false);
							addone.setTextColor(Color.GRAY);
						}
					}
				}) ;

				builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						dialog.dismiss();
					}
				}) ;
				builder.create().show();


				return false;
			}

		});

		typeview.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
									int position, long id) {
				HashMap<String, Object> item=(HashMap<String, Object>) parent.getItemAtPosition(position);
				String tag =  item.get("type").toString();
				totalItem=0;
				if(gv!=-1)
				{
					if(gv==position)
					{
						view.setBackgroundColor(Color.WHITE);
						gv=-1;
						curtype="-1";
						cur = accs.getListDataByType(iyear,imonth,"XX",pagenum,0);
						//显示查询数据
						ListViewAdapter adapter = new ListViewAdapter(twoActivity.this,cur,items);
						listView.setAdapter(adapter);
						listView.setDivider(new ColorDrawable(Color.GRAY));
						listView.setDividerHeight(1);
//
					}else
					{
						View v =  parent.getChildAt(gv);
						v.setBackgroundColor(Color.WHITE);
						view.setBackgroundColor(Color.GRAY);
						gv = position;

						if(!tag.equals(" "))
						{
							curtype=tag;
							cur = accs.getListDataByType(iyear,imonth,tag,pagenum,0);
							//显示查询数据
							ListViewAdapter adapter = new ListViewAdapter(twoActivity.this,cur,items);
							listView.setAdapter(adapter);
							listView.setDivider(new ColorDrawable(Color.GRAY));
							listView.setDividerHeight(1);
						}else
						{
							curtype="-1";
							cur = accs.getListDataByType(iyear,imonth,"XX",pagenum,0);
							//显示查询数据
							ListViewAdapter adapter = new ListViewAdapter(twoActivity.this,cur,items);
							listView.setAdapter(adapter);
							listView.setDivider(new ColorDrawable(Color.GRAY));
							listView.setDividerHeight(1);
						}

					}
				}else
				{
					view.setBackgroundColor(Color.GRAY);
					gv = position;


					if(!tag.equals(" "))
					{
						curtype=tag;

						cur = accs.getListDataByType(iyear,imonth,tag,pagenum,0);
						//显示查询数据
						ListViewAdapter adapter = new ListViewAdapter(twoActivity.this,cur,items);
						listView.setAdapter(adapter);
						listView.setDivider(new ColorDrawable(Color.GRAY));
						listView.setDividerHeight(1);
					}else
					{
						curtype="-1";
						cur = accs.getListDataByType(iyear,imonth,"XX",pagenum,0);
						//显示查询数据
						ListViewAdapter adapter = new ListViewAdapter(twoActivity.this,cur,items);
						listView.setAdapter(adapter);
						listView.setDivider(new ColorDrawable(Color.GRAY));
						listView.setDividerHeight(1);
					}
				}
			}
		});




		newtype = (TextView) this.findViewById(R.id.newtype);
		newtype.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {

				addtype.Builder builder = new addtype.Builder(twoActivity.this);


				builder.create(twoActivity.this,typeview,typeService,iyear,imonth).show();
			}
		});

		//记一笔按钮点击事件

		newtype.setOnLongClickListener(new OnLongClickListener() {

			@Override
			public boolean onLongClick(View v) {

				group.Builder builder = new group.Builder(twoActivity.this);
				builder.create(twoActivity.this,typeService,accs,iyear).show();

				return false;
			}
		});

		addone.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {

				if(curtype.equals("-1"))
				{
					Toast.makeText(twoActivity.this, "请选择分组", Toast.LENGTH_SHORT).show();
				}else
				{
					AddAmt.Builder builder = new AddAmt.Builder(twoActivity.this);


					builder.create(curtype,newtype,typeview,listView,twoActivity.this,accs,iyear,imonth,iday,items,typeService).show();
				}


			}

		});


		listView.setOnScrollListener(new OnScrollListener() {
			private boolean isBottom = false;   //用于标记是否到达顶端
			//listview的状态发送改变时执行
			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				if(isBottom && scrollState==OnScrollListener.SCROLL_STATE_IDLE){
					cur = accs.getListDataByType(iyear,imonth,curtype,pagenum,totalItem);
					ListViewAdapter adapter = (ListViewAdapter)listView.getAdapter();
					for(AccountList acc:cur)
					{
						adapter.getListItems().add(acc);
					}

					adapter.notifyDataSetChanged();
					isBottom = false;
				}
			}
			//在滚动的过程中不断执行
			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
								 int visibleItemCount, int totalItemCount) {
				System.out.println(firstVisibleItem+":"+visibleItemCount+":"+totalItemCount);
				if(firstVisibleItem+visibleItemCount == totalItemCount){
					totalItem=totalItemCount;
					isBottom = true;
				}else{
					isBottom = false;
				}
			}
		});

		listView.setOnItemLongClickListener(new OnItemLongClickListener() {

			@Override
			public boolean onItemLongClick(AdapterView<?> parent, View view,
										   int position, long id) {
				lacc=(AccountList) parent.getItemAtPosition(position);

				aid = lacc.getId();


				AlertDialog.Builder builder = new AlertDialog.Builder(twoActivity.this);
				builder.setMessage("确定要删除吗？");

				builder.setPositiveButton("删除", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						accs.updateBalance(lacc, 0);
						lacc.setId(0);

						ArrayList<AccountList> arr = new ArrayList<AccountList>();
						arr.add(lacc);


						sendEmailTread tread = new sendEmailTread(arr, items,accs);
						tread.start();

						List<AccountList> cur1 = accs.getListDataByType(iyear,imonth,curtype,pagenum,0);
						ListViewAdapter adapter = new ListViewAdapter(twoActivity.this,cur1,items);
						listView.setAdapter(adapter);

//	        			        	        //加载数据
//	        							     List<Map<String, Object>> data = typeService.getData(iyear, imonth);
//	        							     gridadapter2 sim_adapter = new gridadapter2(twoActivity.this, data);
//	        							     typeview.setAdapter(sim_adapter);

						newtype.setText(String.format("%.1f",accs.getZSum("1",iyear,imonth)));

						if(cmonth==imonth && cyear==iyear)
						{
							loadGridData();
							addone.setEnabled(true);
							addone.setTextColor(bcolor);
						}else
						{
							loadGroupData();
							addone.setEnabled(false);
							addone.setTextColor(Color.GRAY);
						}


					}
				}) ;

				builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						dialog.dismiss();
					}
				}) ;
				builder.create().show();
				return false;
			}
		});

	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {

		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {

			Intent intent = new Intent();
			setResult(900,intent);
			curtype="-1";
			finish();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

//	public static void setListViewHeightBasedOnChildren(ListView listView) {

//        ListAdapter listAdapter = listView.getAdapter();
//        if (listAdapter == null) {
//            return;
//        }
//
//        int totalHeight = 0;
//        for (int i = 0; i < listAdapter.getCount(); i++) {
//            View listItem = listAdapter.getView(i, null, listView);
//
//            listItem.measure(0, 0);
//            totalHeight += listItem.getMeasuredHeight();
//
//        }
//
//        ViewGroup.LayoutParams params = listView.getLayoutParams();
//        params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
//
//        listView.setLayoutParams(params);
//    }

	public  void loadGridData()
	{
		//加载数据
		List<Map<String, Object>> data = typeService.getData(iyear, imonth);
		gridadapter2 sim_adapter = new gridadapter2(this, data,curtype);
		typeview.setAdapter(sim_adapter);
	}

	public  void loadGroupData()
	{
		//加载数据
		List<Map<String, Object>> data = typeService.getGroupData(iyear, imonth);
		gridadapter2 sim_adapter = new gridadapter2(this, data,curtype);
		typeview.setAdapter(sim_adapter);
	}






}
